package com.sumqun.mall.web;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.collect.Lists;
import com.octo.captcha.service.CaptchaServiceException;
import com.sumqun.mall.entity.Account;
import com.sumqun.mall.service.AccountService;
import com.sumqun.mall.service.CaptchaService;

@Controller
@RequestMapping(value="/account")
public class AccountController {	  
	
	@Autowired
	private AccountService accountService;	
	 
	private Account account = new Account();	
	List<Account> accountes = new ArrayList<Account>();
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	private String login(String username, String password, String usertype, Model model,HttpServletRequest request,     
            HttpServletResponse response){		 
		System.out.println("account.login "+ "uname"+ username+" pwd "+password+ "utype" +usertype);
		Map opt=new HashMap();
		opt.put("0", "普通");
		opt.put("1", "VIP");
		model.addAttribute("usertypeOptions", opt);
		Boolean v= accountService.verify(username, password, usertype);
		
		Boolean isResponseCorrect =Boolean.FALSE;
        
        String captchaId  = request.getSession().getId();        
        String imgjpcode  = request.getParameter("j_captcha_response");
        // Call the Service method
         try {
             isResponseCorrect = CaptchaService.getInstance().validateResponseForID(captchaId,imgjpcode);
         } catch (CaptchaServiceException e) {
        	 return "/error";
         }
         
		if(username!=null && v){
			account=accountService.getVerifyUser(username, password, usertype);
			model.addAttribute("account", account);
			request.getSession().setAttribute("account", account);			 
			return "profile";		
		}else{
			request.getSession().setAttribute("account", account);
			model.addAttribute("account",new Account());
			return "login";
			//return "redirect:/account";
		}		
	}
	
	@SuppressWarnings("unused")
	@RequestMapping(method=RequestMethod.GET)
	private String logon(String username, String password, String usertype, Model model){	
		Account tmpus=new Account();
		Map opt=new HashMap();
		opt.put("0", "普通");
		opt.put("1", "VIP");
		model.addAttribute("usertypeOptions", opt);
		tmpus.setUsertype(0);
		model.addAttribute("account",tmpus);
		return "login";		 
	}
	
	@RequestMapping(value="list",method=RequestMethod.GET)
	public String list(Model model,HttpServletRequest request,     
            HttpServletResponse response){
		System.out.println("account list");
		int offset = 0;
		int maxPageItems=10; //每页显示行数 pager
		
		try { 
            if (request.getParameter("pager.offset") != null) {   
            	System.out.println("--->"+request.getParameter("pager.offset"));
                  offset = Integer.parseInt(request 
                    .getParameter("pager.offset")); 
            } 
           
            if(request.getParameter("maxPageItems")!=null){   
            	System.out.println("--->"+request.getParameter("maxPageItems"));
                maxPageItems = Integer.parseInt((String) request.getParameter("maxPageItems")); 
            } 
            int total=accountService.findAllCount();
            System.out.println("offset"+offset+" maxpageritem"+maxPageItems);
    		accountes = accountService.findAllAccount(offset,maxPageItems);
    		model.addAttribute("total", total);
    		model.addAttribute("accountes", accountes);	
    		return "/account/list";	
        } catch (Exception e) {            
        	return "/error";	 
        }
		
			
			
	}
	
		
	@RequestMapping(value="add")
	public String add(Model model){
		account=new Account();
		Map opt=new HashMap();
		opt.put("0", "普通");
		opt.put("1", "VIP");
		model.addAttribute("usertypeOptions", opt);
		model.addAttribute("account",account);
		return "/account/edit";
	}
	
	@RequestMapping(value="edit/{uid}")
	public String edit(@PathVariable int uid,Model model){
		
		account=accountService.findAccount(uid);
		System.out.println("edit" +uid +account.toString());
		Map opt=new HashMap();
		opt.put("0", "普通");
		opt.put("1", "VIP");
		model.addAttribute("usertypeOptions", opt);
		model.addAttribute("account",account);
		return "/account/edit";	
	}
	

	@RequestMapping(value="save") 
	public String save(Account account){		 
		if(account.getSex()==null){
			account.setSex("0");			
		}
		if(account.getBirthday()==null){
			account.setBirthday(Date.valueOf("2011-01-01"));
		}
		if(account.getStatus()==null){
			account.setStatus("NEW");
		}
		if(account.getUid()==null){
		    accountService.register(account);
		}else{
			accountService.editAccount(account);
		}
		return "redirect:/account/list";
	}
	
	@RequestMapping(value="view/{uid}")
	public String view(@PathVariable int uid,Model model){
		account=accountService.findAccount(uid);
		model.addAttribute("account",account);
		return "profile";	
	}
	
	@RequestMapping(value="delete/{uid}")
	public String delete(@PathVariable int uid,Model model){
		accountService.removeAccout(uid);
		account=new Account();
		model.addAttribute("account",account);
		return "redirect:/account/list";
	}
	
	public void help(){}

	 
	
 
}
